package net.j4love.spring.boot.webmvc;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author He Peng
 * @create 2017-05-19 15:34
 * @update 2017-05-19 15:34
 * @see
 */

@Configuration
public class MyWebMvcConfiguration {


    /**
     * 用 FastJSON 提供的 HttpMessageConverters 替换 spring 默认的 Jackson
     * FastJson 性能优于 Jackson
     *
     * @author   He Peng
     * @date     2017/5/19 0019 16:07
     * @param
     * @throws
     * @return
     * @see
     */
    @Bean
    public HttpMessageConverters fastJsonConverters() {

        FastJsonHttpMessageConverter4 fastJsonMsgConvter = new FastJsonHttpMessageConverter4();
        fastJsonMsgConvter.setDefaultCharset(Charset.forName("UTF-8"));
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        mediaTypes.add(MediaType.TEXT_HTML);
        fastJsonMsgConvter.setSupportedMediaTypes(mediaTypes);
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        SerializerFeature[] serlzFeats = {SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.SkipTransientField};
        fastJsonConfig.setSerializerFeatures(serlzFeats);
        fastJsonMsgConvter.setFastJsonConfig(fastJsonConfig);
        return new HttpMessageConverters(fastJsonMsgConvter);
    }

}
